// pages/medicalKnowledge/medicalKnowledge.js
const app=getApp()
const db = wx.cloud.database()
//基本跟administration.js文件一样的，去看那个注释
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loading: true,
    sticky:true,
    contentList:[]
  },

  
  
  onLoad(){
    this.getAllData()
    this.setData({
      vanTop:app.globalData.vanTop,
      active:1
    })
  },
  getAllData(){
    db.collection('training').get({
      success:(res)=>{
      this.setData({
        contentList:res.data[0].contentList,
        
      })
      let i = 0
        this._nameMap = new Map()
        this._indexMap = new Map()
        this.data.contentList.map(item => {
          this._nameMap.set(i, item.title)
          this._indexMap.set(i++, 0)
        })
        for (let i = 0; i < this.data.contentList.length; i++) {
          let active = i
          let index = this._indexMap.get(active)
          let name = this._nameMap.get(active)
          this.getContentList(name, index, active)
        }
    }
    })
  },
  getContentList(name, index, active) {
    db.collection("training_moreList").where({
      under: name
    }).skip(index * 18).limit(18).get({
      success: (res) => {
        if (res.data.length !== 0) {
          index++
          this._indexMap.set(active, index)
          this.setData({
            [`contentList[${active}].list`]: this.data.contentList[active].list.concat(res.data)
          })
        }
        this.setData({
          loading: false
        })
      }

    })
  },
  onPullDownRefresh() {
    this.setData({
      loading: true,
      [`contentList${this.data.active}.list`]:""
    })
    
      this.getAllData()
      wx.stopPullDownRefresh()

  },
  clickTabs(e) {
    wx.pageScrollTo({
      scrollTop: 0
  })
    if (e.detail.index > -1) {
      this.setData({
        active: e.detail.index
      })
    } else {
      this.setData({
        active: e.currentTarget.dataset.index
      })
    }
  },
  onReachBottom() {
    this.setData({
      loading: true
    })
    let active = this.data.active
    let index = this._indexMap.get(active)
    let name = this._nameMap.get(active)
    
    this.getContentList(name, index, active)
  },
  tap(e){
    const item=e.currentTarget.dataset.item
    setTimeout(()=>{
      wx.navigateTo({
        url: `../noticeMore/noticeMore?_id=${item._id}&title=${'training'}`,
      })
    },800)
  },
  onShareAppMessage(){},
  onShareTimeline(){},
  onAddToFavorites(){},
})